package com.carloha.finance.tool;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.FontFactoryImp;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfWriter;

/**
 * pdf文件操作工具类
 * @author 草原狼
 * @date 2019-7-13
 */
public class PdfUtil {
	protected static Log log = LogFactory.getLog(PdfUtil.class);
	
	/**
	 * 创建pdf文档，并且设置好默认样式
	 * @return
	 */
	public static Document createPdfDocument() {
		// 创建一个文档（默认大小A4，边距36, 36, 36, 36）
        Document document = new Document();
        // 设置文档大小
        document.setPageSize(PageSize.A4);
        // 设置边距，单位都是像素，换算大约1厘米=28.33像素
        document.setMargins(40, 40, 40, 10);        
		return document;
	}
	
	/**
	 * 创建writer，通过writer将文档写入磁盘
	 * @param document
	 * @param fileName
	 * @return
	 */
	public static PdfWriter getPdfWriter(Document document,String fileName) {		
		try {
			File f = new File(fileName);
			File dir = f.getParentFile();
			if(! dir.exists()) {
				log.info("mkdirs: "+dir);
				dir.mkdirs();
			}			
			if(f.exists() && f.isFile()) {
				f.delete();
			}			
			log.info("dir: "+dir);
			log.info("fileName: "+fileName);
			
			PdfWriter writer = PdfWriter.getInstance(document,new FileOutputStream(fileName));
	        return writer;	
		}catch(Exception e) {
			e.printStackTrace();
		}
		return null;        
	}
	
	
	/**
	 * 注册全部字体并返回
	 * @return
	 */
	public static Font getFont() {
		// 定义字体
        FontFactoryImp ffi = new FontFactoryImp();
        // 注册全部默认字体目录，windows会自动找fonts文件夹的，返回值为注册到了多少字体
        ffi.registerDirectories();
        // 获取字体，其实不用这么麻烦，后面有简单方法
        Font font = ffi.getFont("宋体",BaseFont.IDENTITY_H,BaseFont.EMBEDDED, 12, Font.UNDEFINED, null);
        return font;
	}
	
	
	/**
	 * 压缩图片
	 * @param fileName
	 * @param type 压缩方式 1大图，2小图标
	 * @return
	 */
	public static Image percentImage(Image img,int type) {
		try {
			if(img == null) {
				return null;
			}
			float height = img.getHeight();
			float width = img.getWidth();
			img.setAlignment(Image.MIDDLE);
			float percent = 0;
			if(type == 1) {
				percent = getPercent(height, width);
			}else if(type == 2) {
				percent = getPercent2(height, width);
			}else if(type == 3) {
				percent = getPercent();
			}			
			img.scalePercent(percent);			
			return img;
		}catch(Exception e) {
			e.printStackTrace();
		}		
		return null;
	}	
	
	
	/**
	 * 获取网络输入流转变成Image
	 */
	public static Image getURLImg(String urlStr) {
		try {		   
		    byte[] imgb = HttpUtil.getURLInputStream(urlStr);
		    return Image.getInstance(imgb);		
		}catch(Exception e) {
			log.error(e.getMessage(), e.getCause());
		}
		return null;
	} 	
	
	/**
	 * 按固定比例压缩
	 * @param h
	 * @param w
	 * @return
	 */
	public static int getPercent(float h,float w){
		int p=0;
		float p2 = 0.0f;
		p2 = 530/w*100;		
		p = Math.round(p2);
		return p;
	}
	
	/**
	 * 按固定宽度压缩
	 */
	public static float getPercent() {		    
		return 16f;
	}
	
	/**
	 * 按固定比例压缩
	 * @param h
	 * @param w
	 * @return
	 */
	public static int getPercent2(float h,float w){
		int p=0;
		float p2 = 0.0f;
		p2 = 530/w*200;		
		p = Math.round(p2);
		return p;
	}

	
	/**
	 * 添加图片
	 * @param doc
	 * @param g
	 */
	public static void addImg(Document doc,Image g) {
		if(doc != null && g != null) {
			try {
				doc.add(g);
			} catch (DocumentException e) {				
				e.printStackTrace();
			}
		}
	}
	
	
	/**
	 * 关闭文档，才能输出
	 * @param document
	 * @param writer
	 */
	public static void close(Document document,PdfWriter writer) {
		if(document != null) {
			document.close();	
		}
        if(writer != null) {
        	writer.close();	
        }        
	}   
	
	
	/** 
     * @Description:默认文件名下载方法 
     * @param response 
     * @param filePath 
     * @throws IOException 
     */  
    public static void download(HttpServletResponse response,String filePath) throws Exception{  
         File file = new File(filePath);  
         if(file.isFile()){  
             download(response, file.getName(), filePath);  
         }else{  
             throw new Exception("下载类型不是文件或不存在！");  
         }  
    }  
    
    /** 
     * @Description:自定义下载文件名方法 
     * @param response 
     * @param fileName 
     * @param filePath 
     * @throws IOException 
     */  
    public static void download(HttpServletResponse response, String fileName, String filePath) throws Exception{
    	InputStream is = null;
    	OutputStream os = null;
       try {
        	File file = new File(filePath);  
            if(file.isFile()){  
                long fileLength = file.length();  
                //浏览器下载中文名文件兼容性处理  
                String filaname = new String(fileName.getBytes("gb2312"),"ISO8859-1");  
                // 清空response    
                response.reset();  
                //octet-stream 自动匹配文件类型  
                response.setContentType("application/octet-stream;charset=ISO8859-1");  
                response.setHeader("Content-Disposition","attachment;filename=\"" + filaname + "\"");  
                response.setHeader("Content-Length", String.valueOf(fileLength));  
                is = new FileInputStream(file);  
                os = response.getOutputStream();  
                byte[] b = new byte[2048];    
                while (is.read(b) != -1) {  
                    os.write(b);  
                }                  
                os.flush();                  
            }else{  
                throw new Exception("下载类型不是文件或不存在！");  
            }	
        }catch(Exception e) {
        	throw new RuntimeException(e);
        }finally {
        	close(is);
        	close(os);
        }
    }  
    
    /**
     * 关闭输入流
     * @param is
     */
    private static void close(InputStream is) {
    	try {
    		if(is != null) {
    			is.close();
    		}
    	}catch(Exception e) {
    		throw new RuntimeException(e);
    	}
    }
    
    /**
     * 关闭输出流
     */
    private static void close(OutputStream os) {
    	try {
    		if(os != null) {
    			os.close();
    		}
    	}catch(Exception e) {
    		throw new RuntimeException(e);
    	}
    }

    
}
